package com.tom;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class MyNettyServer {
    public static void main(String[] args) {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.channel(NioServerSocketChannel.class);

        // 创建了一组线程 通过死循环 监控状态 accept read write
        serverBootstrap.group(new NioEventLoopGroup());

        // ServerSocketChannel  SocketChannel
        serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {

            /**
             * channel 接通 监控 accept rw 处理 通过流水线 用handler进行处理 。
             * @param ch {@link NioSocketChannel}
             */
            @Override
            protected void initChannel(NioSocketChannel ch) {
                // ByteBuf 字节--->字符
                ch.pipeline().addLast(new StringDecoder());
                //适配器 模式 ChannelInboundHandlerAdapter
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        //如果没有解码, msg 是一个ByteBuf
                        //ByteBuf buffer = (ByteBuf) msg;
                        // String result = ((ByteBuf) msg).toString(StandardCharsets.UTF_8);
                        System.out.println("result = " + (String) msg);
                    }
                });
            }
        });
        serverBootstrap.bind(8000);
    }
}